import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/widgets/form_select_field.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/bottom_sheet/index.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/widgets/show_datetime_picker.dart";
import "package:flutter/cupertino.dart";


enum PermissionType {
  fingerprint,
  icCard
}
class AddPermission extends StatefulWidget {
  final PermissionType type;
  final Map lockInfo;
  final List renter;
  const AddPermission({super.key, required this.type, required this.lockInfo, required this.renter});

  @override
  State<StatefulWidget> createState() => _AddPermissionState();

}


class _AddPermissionState extends State<AddPermission> {
  Map _params = {
    "name": "",
    "renterId": "",
    "startDate": "",
    "endDate": ""
  };


  bool _disabled() {
    if (_params["name"].isEmpty || _params["renterId"] == null || _params["startDate"] == "" || _params["endDate"] == "") return true;
    return false;
  }


  Future<void> _changeRenter() async {
    Map? popped = await showRoundedBottomSheet(
      builder: (context) => BottomSheetSelect(
        items: widget.renter,
        compare: (item) => item["renterId"] == _params["renterId"],
        itemAsString: (item) => item["name"],
      ),
    );
    print(popped);
    if (popped != null) {
      setState(() {
        _params["name"] = popped?["name"];
        _params["renterId"] = popped?["renterId"];
      });
    }
  }

  void _fingerprintPressed() {
    Map params = {
      "startDate": DateTools.formatYMD(_params["startDate"], format: "{y}-{m}-{d} {h}:{i}:{s}"),
      "endDate": DateTools.formatYMD(_params["endDate"], format: "{y}-{m}-{d} {h}:{i}:{s}"),
      "fingerprintName": _params["name"],
    };
    Stacker.pushNamed(Keys.DEVICE_LOCK_FINGERPRINT_ADD_TIP, arguments: {"info": widget.lockInfo, "params": params});
  }

  void _icCardPressed() {}

  DateTime _transferDateTime(dynamic date) {
    if (date == null) {
      return DateTime.now();
    } else if (date is String && date.isEmpty) {
      return DateTime.now();
    } else if (date is DateTime) {
      return date;
    } else {
      return DateTime.parse(date);
    }
  }
  
  String _title(PermissionType type) {
    switch (type) {
      case PermissionType.fingerprint:
        return "添加指纹";
      case PermissionType.icCard:
        return "添加IC卡";
    }
  }
  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: _title(widget.type),
      child: Container(
        padding: EdgeInsets.all(ThemeVars.paddingPage),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            MenuBlock(
              items: [
                MenuBlockItem(
                  text: "姓名",
                  onTap: _changeRenter,
                  suffix: Text(_params["name"].isEmpty ? "请选择" : _params["name"])
                )
              ],
            ),
            SizedBox(height: 12,),
            MenuBlock(
              items: [
                MenuBlockItem(
                  text: "生效时间",
                  onTap: () {
                    showDatetimePicker(
                      context: context,
                      initialDateTime: _transferDateTime(_params["startDate"]),
                      onchange: (value) => setState(() {
                        _params["startDate"] = value;
                      })
                    );
                  },
                  suffix: Text(DateTools.formatYMD(_params["startDate"], format: "{y}-{m}-{d} {h}:{i}"))
                ),
                MenuBlockItem(
                    text: "失效时间",
                    onTap: () {
                      showDatetimePicker(
                          context: context,
                          initialDateTime: _transferDateTime(_params["endDate"]),
                          onchange: (value) => setState(() {
                            _params["endDate"] = value;
                          })
                      );
                    },
                    suffix: Text(DateTools.formatYMD(_params["endDate"], format: "{y}-{m}-{d} {h}:{i}"))
                )
              ],
            ),
            Padding(
              padding: EdgeInsets.only(top: 60),
              child: Button(
                type: ButtonType.primary,
                onPressed: !_disabled() ? () {
                  widget.type == PermissionType.fingerprint ? _fingerprintPressed() : _icCardPressed();
                } : null,
                child: Text(widget.type == PermissionType.fingerprint ? "下一步" : "确定"),
              ),
            )
          ],
        ),
      ),
    );
  }
}